package com.ihteima.controller;

import com.ihteima.exception.BizException;
import com.ihteima.exception.ResponseCodeEnum;
import com.ihteima.model.vo.UpdatePasswordReqVO;
import com.ihteima.model.vo.UpdateUserInfoReqVO;
import com.ihteima.model.vo.UserInfoRspVO;
import com.ihteima.pojo.Response;
import com.ihteima.pojo.User;
import com.ihteima.service.UserService;
import com.ihteima.utils.JwtUtil;
import com.ihteima.utils.Md5Util;
import com.ihteima.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * ClassName: UserController
 * Package: com.ihteima.controller
 * Description:
 *
 * @Auther gongkaiming
 * @Create 2025/10/26 17:32
 * @Version 1.0
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/registry")
    public Response<?> registry(String username, String password) {
        User userDO = userService.findByName(username);
        if (Objects.isNull(userDO)) {
            return userService.registry(username, password);
        } else {
            return Response.fail("用户已注册");
        }
    }

    @PostMapping("/login")
    public Response<?> login(String username, String password) {
        User userDO = userService.findByName(username);
        if (Objects.isNull(userDO)) {
            throw new BizException(ResponseCodeEnum.LOGIN_FAIL);
        }
        return userService.login(username, password);
    }

    @GetMapping("/userInfo")
    public Response<UserInfoRspVO> userInfo() {
        Long id = ThreadLocalUtil.get();
        User userDO = userService.findById(id);

        if (Objects.isNull(userDO)) {
            throw new BizException(ResponseCodeEnum.USER_NOT_EXIST);
        }

        UserInfoRspVO userInfoRspVO = UserInfoRspVO.builder()
                .id(userDO.getId())
                .username(userDO.getUsername())
                .avatar(userDO.getAvatar())
                .email(userDO.getEmail())
                .createTime(userDO.getCreateTime())
                .updateTime(userDO.getUpdateTime())
                .build();

        return Response.success(userInfoRspVO);
    }

    @PostMapping("/update")
    public Response<?> updateUser(@RequestBody UpdateUserInfoReqVO updateUserInfoReqVO) {
        return userService.updateUserInfo(updateUserInfoReqVO);
    }
    
    @PostMapping("/updatePassword")
    public Response<?> updatePassword(@RequestBody UpdatePasswordReqVO updatePasswordReqVO) {
        return userService.updatePassword(updatePasswordReqVO);
    }
}
